import { Button, Form, Input, Space, message as antdMessage } from "antd";
import styles from "./style.module.scss";
import axios from "axios";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../../store/userSlice/userSlice";

import { useAuth } from "../../hooks/useAuth";

interface LoginStateType {
  username: string;
  password: string;
}

const Login = () => {
  const dispatch = useDispatch();
  const onFinish = async (values: LoginStateType) => {
    console.log("values", values);
    const resp = await axios.post("/api/login", values);
    const { code, data, message } = resp.data;
    if (code === 10000) {
      antdMessage.success(message);
      // 存储本地 ｜ 仓库
      dispatch(loginSuccess(data));
    } else {
      antdMessage.error(message);
    }
  };

  useAuth();
  return (
    <div className={styles.container}>
      <div className={styles.login}>
        <Form onFinish={onFinish}>
          <Form.Item>
            <h1 className={styles.title}>用户登陆</h1>
          </Form.Item>
          <Form.Item
            rules={[
              {
                required: true,
                message: "用户名不可以为空",
              },
            ]}
            label="用户名"
            labelCol={{ span: 3 }}
            name="username"
          >
            <Input placeholder="请输入用户名" autoComplete=""></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            labelCol={{ span: 3 }}
            name="password"
            rules={[
              {
                required: true,
                message: "密码不可以为空",
              },
            ]}
          >
            <Input.Password placeholder="请输入密码" autoComplete=""></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 3 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                登陆
              </Button>
              <Button type="primary" danger>
                注册
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
